import React, { useState, useEffect } from 'react';
import classnames from 'classnames';
import moment from 'moment';
import { connect } from 'dva';
import { Button, Form, Select, Table, Empty, Modal, message } from 'antd';
import TPage from '@/modules/TPage';
import CreateModal from './modules/CreateModal';
import Service from '@/public/http/services';
import { DocumentType, OnOrOffState } from '@/public/constant/enums';
import style from './index.css';
const { Option } = Select;
const { Column } = Table;
const List: React.FC<any> = ({ total, list, dispatch }) => {
  const [curPage, setCurPage] = useState(1);
  const [curName, setCurName] = useState(null);
  const [aihao, setAihao] = useState([]);

  const pageSize = 10;
  /**
   * 加载列表数据
   */
  function fetchList({ page, name }) {
    dispatch({
      type: 'storedocuments/fetchList',
      payload: {
        page,
        name,
        pageSize
      }
    })
  }

  /**
   * @desc 操作完更新列表
   */
  function reFetchList() {
    fetchList({
      page: curPage,
      name: curName
    })
  }

  function getinterest(){
    Service.queryAllAihao().then((res) => {
      setAihao(res as any)
    })
  }

  useEffect(({ page = curPage, name = curName } = {}) => {
    fetchList({ page, name })
    getinterest()
  }, [curPage, curName])
  // 渲染列表查询表单

  const handleQuery = (query) => {
    setCurPage(1);
    setCurName(query);
  }

  function renderTableForm() {
    const WrappedForm = Form.create<any>({ name: 'tableForm' })(function ({ form }) {
      const { getFieldDecorator } = form as any;
      return (
        <Form onSubmit={handleQuery.bind(null, form)} layout={'inline'}>

        </Form>
      );
    })
    return (
      <WrappedForm />
    );
  }

  // 根据渲染类型渲染列表
  const renderActions =
    (record: any) => {
      const { state } = record;
      return (
        <>
          {
            state === 1 ? <>
                <Button className={style.mr8} type={'ghost'} onClick={() => { handleOnline(record); }}>上架</Button>
              </>
              :
              <Button className={style.mr8} type={'ghost'} onClick={() => { handleOffnline(record); }}>下架</Button>
          }
          <Button className={style.mr8} type={'primary'} onClick={() => { handleEdit(record) }}>编辑</Button>
        </>
      );
    }

  /**
   * @desc 上架
   */
  const handleOnline = ({ id }) => {
    Modal.confirm({
      title: '确定上架吗？',
      okText: '上架',
      cancelText: '取消',
      onOk: () => {
        Service.onlineStoreDocument(id).then(() => {
          message.info('上架成功');
          reFetchList();
        })
      }
    });
  }

  /**
   * @desc 下架
   */
  const handleOffnline = ({ id }) => {
    Modal.confirm({
      title: '确定下架吗？',
      okText: '下架',
      cancelText: '取消',
      onOk: () => {
        Service.offlineStoreDocument(id).then(() => {
          message.info('下架成功');
          reFetchList();
        })
      }
    });
  }

  const [formModalVisible, setFormModalVisible] = useState(false);
  const [curModalStatus, setCurModalStatus] = useState(0);

  /**
   *
   * @desc 创建
   */
  const handleCreate = () => {
    setCurModalStatus(0);
    setFormModalVisible(true);
  }

  const [curEditInfo, setCurEditInfo] = useState({})
  /**
   *
   * @desc 编辑
   */
  const handleEdit = (record) => {
    setCurModalStatus(1);
    setCurEditInfo(record);
    setFormModalVisible(true);
  }

  /**
   * @desc 创建提交
   */
  const handleSubmit = (form: any, { authorPortraits, urls, coverImgs, summary }, type) => {
    const { validateFields, resetFields } = form;
    const status = type;
    validateFields((err, value) => {
      if (!err) {
        const { name, type, author, keywords,isVip } = value;
        const params = {
          coverImg: (coverImgs[0] as any).url,
          authorPortrait: (authorPortraits[0] as any).url,
          url: (urls[0] as any).url,
          name,
          type,
          author,
          keywords,
          summary,
          isVip,
          tags:form.tags
        };

        (status ? Service.createStoreResource(params) : Service.updateStoreResource({ id: curEditInfo['id'], ...params })).then(() => {
          message.info(`${type ? '添加' : '修改'}成功`);
          resetFields();
          setCurEditInfo({});
          setFormModalVisible(false);
          reFetchList();
        })
      }
    })
  }

  /**
   *
   * @desc 创建/编辑取消
   */
  const handleCancel = (form) => {
    form.resetFields();
    setCurEditInfo({});
    setFormModalVisible(false);
  }

  return (
    <TPage>
      <TPage.Title>商城文库</TPage.Title>
      <TPage.Table>
        <TPage.Layout className={style.btns}>
          <Button type={'primary'} onClick={handleCreate}>新建</Button>
          <TPage.Search
            placeholder={'请输入资料名称，可按回车键搜索'}
            onSearch={handleQuery}
          />
        </TPage.Layout>
        <Table
          className={classnames(style.mt16, style.document_list)}
          locale={{ emptyText: <Empty description={'无数据'} /> }}
          dataSource={list}
          pagination={{ total, current: curPage, pageSize, onChange: setCurPage }}
          rowKey={(record: any) => record.id}
          scroll={{ x: 2000 }}
        >
          <Column title={'编号ID'} width={64} dataIndex={'id'} key={'id'} />
          <Column title={'资料名称'} width={320} key={'name'}
                  render={(value, record: any) => {
                    return <span className={style.mainPicUnit}>
                < img src={record.coverImg} />
                      {record.name}
              </span>
                  }} />
          <Column title={'作者'} key={'author'}
                  render={(value, record: any) => {
                    return <span className={style.thumbnail}>
                < img src={record.authorPortrait} />
                      {record.author}
              </span>
                  }}
          />
          <Column title={'资料类型'} dataIndex={'type'} key={'type'} render={value => DocumentType[value]} />
          <Column title={'资料大小(MB)'} dataIndex={'size'} key={'size'} />
          <Column title={'关键词'} dataIndex={'keywords'} key={'keywords'} />
          <Column title={'下载量'} key={'count'} />
          <Column title={'资料地址'} dataIndex={'url'} key={'url'} width={280} render={value => <a href={value} className={style['file-link']}>{value}</a>} />
          <Column title={'更新时间'} dataIndex={'uTime'} key={'uTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
          <Column title={'创建时间'} dataIndex={'createTime'} key={'createTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
          <Column title={'状态'} width={100} dataIndex={'state'} key={'state'} render={(value) => <span className={style[value === 1 ? 'offline' : 'online']}>{OnOrOffState[value]}</span>} />
          <Column title={'操作'} key={'act'} render={renderActions} fixed={'right'} />
        </Table>
      </TPage.Table>
      <CreateModal visible={formModalVisible}
                   title={curModalStatus === 0 ? '文库创建' : '文库编辑'}
                   formData={curModalStatus === 0 ? {} : curEditInfo}
                   interlist={aihao}
                   onOK={(form, data) => handleSubmit(form, data, curModalStatus === 0)}
                   onCancel={handleCancel} />
    </TPage>
  );
}
export default connect((state: any) => {
  return {
    list: state.storedocuments.list,
    total: state.storedocuments.total,
  };
})(List);
